package mysql

import (
	"gorm.io/gorm"
	"video-joy/userrpc/userrpc"
)

type VideoInfo struct {
	gorm.Model
	UserId        int64  `gorm:"type:int(11);not null"`
	VideoTitle    string `gorm:"type:varchar(30);not null"`
	VideoCategory string `gorm:"type:varchar(30);not null"`
	VideoLink     string `gorm:"type:varchar(500);not null"`
	CoverLink     string `gorm:"type:varchar(500);not null"`
	VideoIntro    string `gorm:"type:varchar(500);"`
	PlayNum       int    `gorm:"type:int(11);not null"`
	LikeNum       int    `gorm:"type:int(11);not null"`
	CollectNum    int    `gorm:"type:int(11);not null"`
	VideoStatus   int    `gorm:"type:int(11);not null"`
	TopicId       int    `gorm:"type:int(11);not null"`
}

func (i *VideoInfo) VideoAdd(db *gorm.DB) error {
	return db.Debug().Create(i).Error
}

func (i *VideoInfo) VideoUpdate(db *gorm.DB) error {
	return db.Debug().Updates(i).Error
}

func (i *VideoInfo) VideoDel(db *gorm.DB, id int64) error {
	return db.Debug().Where("video_infos.id", id).Delete(i).Error
}

func (i *VideoInfo) VideoById(db *gorm.DB, id int64) error {
	return db.Debug().Where("video_infos.id=?", id).First(i).Error
}

func (i *VideoInfo) VideoFindById(db *gorm.DB, id int64) error {
	return db.Debug().Where("video_infos.id=?", id).First(i).Error
}

/*
SELECT
  user_infos.id,
  video_infos.video_title,
  video_infos.cover_link,
  video_infos.play_num
FROM
  video_infos
  LEFT JOIN user_infos ON video_infos.user_id = user_infos.id
*/

func VideoList(db *gorm.DB, in *userrpc.VideoListRequest) []*userrpc.VideoList {
	var video []*userrpc.VideoList

	tx := db.Debug().Model(&VideoInfo{}).
		Select(
			"video_infos.*",
			"user_infos.id",
			"video_infos.video_title",
			"video_infos.cover_link",
			"video_infos.play_num").
		Joins("LEFT JOIN user_infos ON video_infos.user_id = user_infos.id").
		Where("video_infos.user_id=?", in.UserId).
		Order("video_infos.play_num desc").
		Scopes(Paginate(int(in.Page), int(in.PageSize)))

	if in.SortType == 0 {
		tx = tx.Order("video_infos.play_num desc")
	}
	if in.SortType == 1 {
		tx = tx.Order("video_infos.created_at desc")
	}

	tx.Find(&video)

	return video
}
